<?php

namespace Pig\Controller;

class GoodsController extends BaseController {

    private $tca = array();
    public $tbName = CONTROLLER_NAME; 
    public $image_path = '';
    protected function init() {
        /*商品分类*/
        $Category = M('category');
        $categories = $Category->Field('id as "0",name as "1"')->order('crdate desc')->select();
        $this->assign('categories',$categories);
        $type = array(
            array(0,'单规格'),
            array(1,'多规格')
        );
        //多图
        $multiple =array();
        $id = I('request.id',0);
        if($id){
            //批量图片
            $data = array(
                    'info_tab' => CONTROLLER_NAME,
                    'info_id' => $id
            );
            $multiple = M('Attach')->where($data)->select();

            if (count($multiple)) {
                foreach ($multiple as $k => $v) {
                    $multiple[$k]['path'] = $this->Config['path_upload'] . CONTROLLER_NAME.'/attach/' . date('Ym', $v['crdate']) . '/' . $v['path'];
                }
            }
        }
        //配置字段
        $this->tca = array(
            'hidden' => array(
                'label' => '是否上架',
                'type' => 'toggle_button',
                'data' => 0
            ),
            'category_id' => array(
                'label' => '选择分类',
                'type' => 'select',
                'data' => $categories,
                'required' => true
            ),
            'name' => array(
                'label' => '商品名称',
                'type' => 'text',
                'required' => true
            ),
            'remark' => array(
                'label' => '商品标签',
                'type' => 'textarea',
                'required' => true,
                'help' => '多个标签用英文,隔开'
            ),
            'title' => array(
                'label' => '服务标题',
                'type' => 'textarea',
                'required' => true,
                'help' => '多个标题用英文,隔开'
            ),
            'service' => array(
                'label' => '服务内容',
                'type' => 'textarea',
                'required' => true,
                'help' => '多个内容用英文,隔开'
            ),
            'origin_area' => array(
                'label' => '产地',
                'type' => 'text',
                'required' => true
            ),
            'type' => array(
                'label' => '商品规格',
                'type' => 'radio',
                'data' => $type,
                'default' => 0
            ),
            'skus' => array(
                'label' => '商品编码',
                'type' => 'text',
                'validate' => [
                    ['/\S/','商品编码不能为空'],
                ],
                'relation' => ['type',0],
            ),
            'sale_prices' => array(
                'label' => '零售价',
                'type' => 'text',
                'validate' => [
                    ['/^[0-9]+(.[0-9]{1,2})?$/','请输入正确的零售价'],
                ],
                'relation' => ['type',0],
                'help' => '零售价为整数或精确到小数点后一位或两位的数值'
            ),
            'cost_prices' => array(
                'label' => '成本价',
                'type' => 'text',
                'validate' => [
                    ['/^[0-9]+(.[0-9]{1,2})?$/','请输入正确的成本价'],
                ],
                'relation' => ['type',0],
                'help' => '成本价为整数或精确到小数点后一位或两位的数值'
            ),
            'distribution_prices' => array(
                'label' => '分销价',
                'type' => 'text',
                'validate' => [
                    ['/^[0-9]+(.[0-9]{1,2})?$/','请输入正确的分销价'],
                ],
                'relation' => ['type',0],
                'help' => '分销价为整数或精确到小数点后一位或两位的数值'
            ),
            'stocks' => array(
                'label' => '库存',
                'type' => 'text',
                'validate' => [
                    ['/\\d/','请输入正确的库存'],
                ],
                'relation' => ['type',0],
                'help' => '库存为0或者正整数'
            ),
            'postage_price' => array(
                'label' => '运费',
                'type' => 'text',
                'required' => true,
                'validate' => [
                    ['/^[0-9]+(.[0-9]{1,2})?$/','请输入正确的运费'],
                ],
                'help' => '运费为整数或精确到小数点后一位或两位的数值'
            ),
            'suggest_start_price' => array(
                'label' => '参团最低参考价',
                'type' => 'text',
                'required' => true,
                'validate' => [
                    ['/^[0-9]+(.[0-9]{1,2})?$/','请输入正确的参团最低参考价'],
                ],
                'help' => '参团最低参考价为整数或精确到小数点后一位或两位的数值'
            ),
            'suggest_end_price' => array(
                'label' => '参团最高参考价',
                'type' => 'text',
                'required' => true,
                'validate' => [
                    ['/^[0-9]+(.[0-9]{1,2})?$/','请输入正确的参团最高参考价'],
                ],
                'help' => '参团最高参考价为整数或精确到小数点后一位或两位的数值'   
            ),
            'image' => array(
                'label' => '商品图片',
                'type' => 'image',
                'name' => 'image',
                'required' => true,
                'help' => '建议上传尺寸:长180px 宽180px'
            ),
            'links' => array(
                'label' => '视频链接',
                'type' => 'text',
                'help' => '请填写完成的视频链接,如：https://www.baidu.com'
            ),
            'multiple' => array(
                'label' => '商品轮播图',
                'type' => 'multiple',
                'data' => $multiple,
                'help' => '建议上传尺寸:长640px 宽640px'
            ),
            'content' => array(
                'label' => '商品描述',
                'type' => 'rte',
                'required' => true
            ),
        );
    }

    /*
     * 列表页面
     */

    public function index() {
        $Obj = D($this->tbName); //实例化对象
        $Where = "deleted=0";
         /*关键字查询*/   
        if (I('request.name')!='') {
            $I_keyword = trim(I('request.name'));
            $Where .= " and (name like '%" . $I_keyword . "%')";
        }
        //控制分页显示条数
        if(I('post.limit_num')!=''){
            session('page_limit_num', I('post.limit_num'));
        }
        //控制列表排序
        $sorting = I('get.sorting') ? I('get.sorting') : 'id';
        $order = I('get.order') ? I('get.order') : 'desc';
        
        $limit_num = $_SESSION['page_limit_num'] ? $_SESSION['page_limit_num'] : 10;//客户列表默认10条
        
        $Page = new \Pig\Util\Page($list_sum = $Obj->where($Where)->count(), $offset = $limit_num); // 实例化分页类 传入总记录数和每页显示的记录数
        $list = $Obj
                ->where($Where)
                ->order($sorting.' '.$order)
                ->limit($Page->firstRow . ',' . $Page->listRows)
                ->select();
        $Goodsinfo = M('goods_info');
        foreach ($list as $key => &$value) {
            $value['info'] = $Goodsinfo->where(array('goods_id' => $value['id'],'deleted' => 0))->select();
        }
        $this->assign('list', $list); // 赋值数据集
        $this->assign('page', $Page->show()); // 分页显示输出
        $this->display(); // 输出模板
    }

    /*
     * 编辑数据
     */

    public function edit() {
        $this->save();
    }

    /*
     * 保存数据
     */

    public function save() {
        try{
            $this->init();
            //编辑数据
            $id = I('request.id') ? I('request.id') : null;
            $info = M($this->tbName)->where('id = ' . $id)->find();
            if (IS_POST) {
                /*页面原始必填项验证-start*/
                foreach ($_POST as $key => $val) {
                    if(@$this->tca[$key]['required'] && !preg_match('/\S/', $val)){
                        $this->error($this->tca[$key]['label'] . '*是必填项!');
                    }
                    //数据验证
                    if(isset($this->tca[$key]['validate'])){
                        if($_POST[$this->tca[$key]['relation'][0]] == $this->tca[$key]['relation'][1]){
                            foreach ($this->tca[$key]['validate'] as $value) {
                                if(!preg_match($value[0], $val)){
                                    $this->error($value[1]);
                                }
                            }
                        }
                    }
                }
                /*存在规格*/
                if(isset($_POST['assistant'])){
                    foreach ($_POST['assistant'] as $key => $value) {
                        foreach ($value as $k => $v) {
                            if(!$v){
                                $this->error('请完善商品规格');
                            }
                        }   
                    }
                    foreach ($_POST['sku'] as $key => $value) {
                        if(!$value){
                            $this->error('请完善商品编码');
                        }
                    }
                    foreach ($_POST['sale_price'] as $key => $value) {
                        if(!preg_match('/^[0-9]+(.[0-9]{1,2})?$/', $value)){
                            $this->error('请填写正确的零售价');
                        }
                    }
                    foreach ($_POST['cost_price'] as $key => $value) {
                        if(!preg_match('/^[0-9]+(.[0-9]{1,2})?$/', $value)){
                            $this->error('请填写正确的成本价价');
                        }
                    }
                    foreach ($_POST['distribution_price'] as $key => $value) {
                        if(!preg_match('/^[0-9]+(.[0-9]{1,2})?$/', $value)){
                            $this->error('请填写正确的分销价');
                        }
                    }
                    foreach ($_POST['stock'] as $key => $value) {
                        if(!preg_match('/\\d/', $value)){
                            $this->error('请填写正确的库存');
                        }
                    }
                }
                $info = M($this->tbName)->where('id = ' . $id)->find();
                //删除文件 begin **********************************
                $path = $this->Config['path_upload'] . CONTROLLER_NAME . '/';
                if ($info && $info['image'] && $_POST['delete_image'] == '1') {
                    $file_path = $path . date('Ym', $info['crdate']) . '/';
                    $this->delInfoFile($file_path, $info['image']);
                } else {
                    unset($_POST['image']);
                }
                //删除文件 end **********************************
                
                //文件上传 begin **********************************
                if (count($_FILES) && isset($_FILES['image'])) {
                    $save_path = ''; // 设置附件上传目录
                    $extent_path = ($info['crdate'] ? date('Ym', $info['crdate']) : date('Ym')) . '/';
                    $thumb_width = 375;
                    $thumb_height = 130;
                    $upload = $this->uploadFile('image', $path, $save_path, $extent_path, $thumb_width, $thumb_height);
                    if (is_array($upload) && $upload['upload']) {
                        $_POST['image'] = $upload['info'];
                    } else {
                        $this->error($upload['info']);
                    }
                }
                //文件上传 end **********************************
                $Obj = D($this->tbName);
                $Obj->startTrans();
                $result = $Obj->create();
                if (!$result) {
                    $this->error($Obj->getError());
                } else { 
                    if(!isset($_POST['hidden'])){
                        $Obj->hidden = 1;
                    }  
                    $Goodsinfo = M('goods_info');     
                    if ($id) {
                        $Obj->tstamp = time();
                        $state = $Obj->where(array('id' => $id))->save();
                        if(!$state){
                            debug($Obj->_sql());
                            $this->error('编辑失败');
                            exit;
                        }
                        //编辑判断商品是多规格还是单规格
                        $goods_info = $Goodsinfo->where(array('goods_id' => $id,'deleted' => 0))->select();
                        if($_POST['type'] == 0){
                            $info_data = [
                                'sku' => $_POST['skus'],
                                'sale_price' => $_POST['sale_prices'],
                                'cost_price' => $_POST['cost_prices'],
                                'distribution_price' => $_POST['distribution_prices'],
                                'stock' => $_POST['stocks'],
                                'tstamp' => time()
                            ];
                            if($info['type'] == 0){
                                $num = $Goodsinfo->where(['id' => $goods_info[0]['id']])->save($info_data);
                                if(!$num){
                                    $Obj->rollback();
                                    debug($Goodsinfo->_sql());
                                    $this->error('编辑失败');
                                }
                            }else{
                                $info_ids = [];
                                $info_ids = array_map(function($value){
                                    return $info_ids[] = $value['id'];
                                },$goods_info);
                                //删除之前保存的多商品规格
                                $num = $Goodsinfo->where(['id' => ['IN',$info_ids]])->save(['deleted' => 1,'tstamp' => time()]);
                                if(!$num){
                                    $Obj->rollback();
                                    debug($Goodsinfo->_sql());
                                    $this->error('编辑失败');
                                }
                                //保存新增的商品规格
                                $info_data['crdate'] = time();
                                $flag = $Goodsinfo->add($info_data);
                                if(!$flag){
                                    $Obj->rollback();
                                    debug($Goodsinfo->_sql());
                                    $this->error('编辑失败');
                                }
                            }
                        }else{
                            if($info['type'] == 0){
                                //删除之前保存的单规格
                                $num = $Goodsinfo->where(['id' => $goods_info[0]['id']])->save(['deleted' => 1,'tstamp' => time()]);
                                if(!$num){
                                    $Obj->rollback();
                                    debug($Goodsinfo->_sql());
                                    $this->error('编辑失败');
                                }
                                //保存多规格
                                foreach($_POST['assistant'] as $key => $value){
                                    $info_data = [
                                        'goods_id' => $id,
                                        'assistant' => $value,
                                        'sku' => $_POST['sku'][$key],
                                        'sale_price' => $_POST['sale_price'][$key],
                                        'cost_price' => $_POST['cost_price'][$key],
                                        'distribution_price' => $_POST['distribution_price'][$key],
                                        'stock' => $_POST['stock'][$key],
                                        'crdate' => time(),
                                        'tstamp' => time()
                                    ];
                                    $flag = $Goodsinfo->add($info_data);
                                    if(!$flag){
                                        $Obj->rollback();
                                        debug($Goodsinfo->_sql());
                                        $this->error('编辑失败');
                                    }
                                }
                            }else{
                                //计算已删除的规格
                                $info_ids = [];
                                $info_ids = array_map(function($value){
                                    return $info_ids[] = $value['id'];
                                },$goods_info);
                                $del_ids = [];
                                foreach ($info_ids as $key => $value) {
                                    if(!in_array($value,$_POST['info_id'])){
                                        $del_ids[] = $value;
                                    }
                                }
                                //对删除的规格做处理
                                if($del_ids){
                                    $num = $Goodsinfo->where(['id' => ['IN',$del_ids]])->save(['deleted' => 1,'tstamp' => time()]);
                                    if(!$num){
                                        $Obj->rollback();
                                        debug($Goodsinfo->_sql());
                                        $this->error('编辑失败');
                                    }
                                }
                                
                                //保存多规格
                                foreach($_POST['assistant'] as $key => $value){
                                    $info_data = [
                                        'goods_id' => $id,
                                        'assistant' => $value,
                                        'sku' => $_POST['sku'][$key],
                                        'sale_price' => $_POST['sale_price'][$key],
                                        'cost_price' => $_POST['cost_price'][$key],
                                        'distribution_price' => $_POST['distribution_price'][$key],
                                        'stock' => $_POST['stock'][$key],
                                        'tstamp' => time()
                                    ];
                                    if($_POST['info_id'][$key]){
                                        $flag = $Goodsinfo->where(['id' => $_POST['info_id'][$key]])->save($info_data);
                                    }else{
                                        $info_data['crdate'] = time();
                                        $flag = $Goodsinfo->add($info_data); 
                                    }
                                    if(!$flag){
                                        $Obj->rollback();
                                        debug($Goodsinfo->_sql());
                                        $this->error('编辑失败');
                                    }
                                }
                            }
                        }
                        $message = '编辑成功!';
                    } else {
                        $Obj->crdate = time();
                        $Obj->tstamp = time();
                        $id = $Obj->add();
                        if(!$id){
                            debug($Obj->_sql());
                            $this->error('添加失败');
                            exit;
                        }
                        if($_POST['type'] == 0){
                            $info_data = [
                                'goods_id' => $id,
                                'sku' => $_POST['skus'],
                                'sale_price' => $_POST['sale_prices'],
                                'cost_price' => $_POST['cost_prices'],
                                'distribution_price' => $_POST['distribution_prices'],
                                'stock' => $_POST['stocks'],
                                'tstamp' => time(),
                                'crdate' => time()
                            ];
                            //保存新增的商品规格
                            $info_data['crdate'] = time();
                            $flag = $Goodsinfo->add($info_data);
                            if(!$flag){
                                $Obj->rollback();
                                debug($Goodsinfo->_sql());
                                $this->error('新增失败');
                            }
                        }else{
                            //保存多规格
                            foreach($_POST['assistant'] as $key => $value){
                                $info_data = [
                                    'goods_id' => $id,
                                    'assistant' => $value,
                                    'sku' => $_POST['sku'][$key],
                                    'sale_price' => $_POST['sale_price'][$key],
                                    'cost_price' => $_POST['cost_price'][$key],
                                    'distribution_price' => $_POST['distribution_price'][$key],
                                    'stock' => $_POST['stock'][$key],
                                    'crdate' => time(),
                                    'tstamp' => time()
                                ];
                                $flag = $Goodsinfo->add($info_data);
                                if(!$flag){
                                    $Obj->rollback();
                                    debug($Goodsinfo->_sql());
                                    $this->error('编辑失败');
                                }
                            }
                        }
                        $message = '添加成功!';
                    }   
                }
                //多文件上传 begin
                if (isset($_POST['multiple'])) {
                    foreach ($_POST['multiple'] as $file) {
                        if ($file) {
                            $file = explode('/', trim($file));
                            if (empty($file[0]) || empty($file[1])){
                                continue;
                            }

                            $file_info = array(
                                'tstamp' => time(),
                                'crdate' => time(),
                                'title' => substr($file[1], 0, strrpos($file[1], '.')),
                                'info_id' => $id,
                                'info_tab' => CONTROLLER_NAME,
                                'path' => $file[0],
                            );
                            $attch_id = M('Attach')->add($file_info);
                            if(!$attch_id){
                                $Obj->rollback();
                                debug(M()->_sql());
                                $this->error('多图保存失败');
                            }
                        }
                    }
                }
                //多文件上传 end ************************************
                $Obj->commit();
                $this->success($message,U(CONTROLLER_NAME.'/index'));
                
            }
            $goods_info = [];
            if($info){
                $goods_info = M('goods_info')->where(array('goods_id' => $id,'deleted' => 0))->select();
            }
            if($info['type'] == 1){
                $html = '<div class="ass"><div class="control-group"><div class="controls"><button id="add" type="button" class="btn green">添加规格 <i class="icon-save"></i></button></div></div><div class="controls"><div class="propertyTable"><div class="tabHead clearfix"><span>规格名称</span><span>商品编码</span><span>零售价</span><span>成本价</span><span>分销价</span><span>库存</span><span>操作</span></div><div class="tabBody">';
                foreach ($goods_info as $key => $value) {
                    $html .= '<div class="item clearfix">';
                    $html .= '<input type="hidden" name="info_id[]" value="'.$value['id'].'" />';
                    $html .= '<span><input name="assistant[]" type="text" class="setInp" value="'.$value['assistant'].'" /></span>';
                    $html .= '<span><input name="sku[]" type="text" class="setInp" value="'.$value['sku'].'" /></span>';
                    $html .= '<span><input name="sale_price[]" type="text" class="setInp" value="'.$value['sale_price'].'" /></span>';
                    $html .= '<span><input name="cost_price[]" type="text" class="setInp" value="'.$value['cost_price'].'" /></span>';
                    $html .= '<span><input name="distribution_price[]" type="text" class="setInp"value="'.$value['distribution_price'].'" /></span>';
                    $html .= '<span><input name="stock[]" type="text" class="setInp"value="'.$value['stock'].'" /></span>';
                    $html .= '<span><i class="icon-trash trash"></i></span></div>';
                }
                $html .= '</div></div></div>';
            }
            if($info && $info['type'] == 0){
                $info['skus'] = $goods_info[0]['sku'];
                $info['sale_prices'] = $goods_info[0]['sale_price'];
                $info['cost_prices'] = $goods_info[0]['cost_price'];
                $info['distribution_prices'] = $goods_info[0]['distribution_price'];
                $info['stocks'] = $goods_info[0]['stock'];
            }
            $this->assign('html',$html);
            $this->assign('info',$info);
            parent::autoFields($this->tca, $info);
            $this->assign('Multiple', true);
            $this->display('info');
        }catch(\Exception $e){
            debug($e->getmessage());
            $this->error('保存失败');
        }
    }
}

?>